package com.bum.sock.poll.bo;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.catalina.comet.CometEvent;

public class EventBO {
	private static final ConcurrentMap<String, Map<String, CometEvent>>	events	= new ConcurrentHashMap<String, Map<String, CometEvent>>();

	public void destroy() {
		events.clear();
	}

	public void add(CometEvent event, String id, String sessionId) {
		if (sessionId == null) {
			return;
		}

		Map<String, CometEvent> userEvents = events.get(sessionId);

		if (userEvents == null) {
			final Map<String, CometEvent> eventSet = new HashMap<String, CometEvent>();

			// kq trả về item trước đó nếu có
			userEvents = events.putIfAbsent(sessionId, eventSet);
			if (userEvents == null) {
				userEvents = eventSet;
			}
		}
//		else {
//			userEvents.removeAll(Collections.singleton(null));
//		}

		userEvents.put(id, event);

		events.put(sessionId, userEvents);
	}

//	private String getOwner(CometEvent event, boolean genSession) {
//		return event.getHttpServletRequest().getSession(genSession).getId();
//	}

	public Map<String, CometEvent> get(String user) {
		if (user == null) {
			return null;
		}
		return events.get(user);
	}

	public void remove(String sessionId) {
		if (!events.containsKey(sessionId)) {
			return;
		}

		Map<String, CometEvent> map = events.get(sessionId);
		for (CometEvent event : map.values()) {
			try {
				event.close();
			} catch (IOException e) {
			}
		}
		events.remove(sessionId);
	}

	public void remove(CometEvent event, String id, String sessionId) {
		if (event == null) {
			return;
		}

		if (sessionId == null) {
			return;
		}

		Map<String, CometEvent> userEvents = null;
		if (events.containsKey(sessionId)) {
			userEvents = events.get(sessionId);
			userEvents.remove(id);
		}

		if (userEvents.isEmpty()) {
			events.remove(sessionId);
		} else {
			events.put(sessionId, userEvents);
		}
	}

	public boolean contains(String key) {
		return events.containsKey(key);
	}
}
